package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * app端用户登录拦截
 *
 * @Author ilurfucy
 * @Date 2022/8/26     17:28
 * @Description app端用户登录拦截
 **/

@Order(-1)
@Component
public class AppLoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 判断是否为登录请求
        boolean loginRequest = request.getURI().getPath().contains("/login");
        if (loginRequest) {
            // 登录请求，不需要令牌，直接放行
            return chain.filter(exchange);
        }
        // 判断令牌是否存在以及令牌合法性
        String token = request.getHeaders().getFirst("token");
        // 获取令牌claimsBody
        try {
            // 尝试解析令牌
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            {
                // todo 判断令牌权限
            }
            return chain.filter(exchange);
        } catch (Exception e) {
            // 解析失败，令牌不合法
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

    }
}
